package com.itany.nmms.service.impl;

import com.itany.nmms.constant.StatusConstant;
import com.itany.nmms.dao.ProductTypeDao;
import com.itany.nmms.entity.ProductType;
import com.itany.nmms.exception.ProductTypeExistException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.service.ProductTypeService;
import com.itany.nmms.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ProductTypeServiceImpl implements ProductTypeService {

    @Autowired(required = false)
    private ProductTypeDao typeDao;

    @Override
    public void addType(String name) throws RequestParameterErrorException, ProductTypeExistException {
        if(ParameterUtil.isNull(name)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        // 判断当前添加的商品类型名称是否已经存在
        ProductType selectType = typeDao.selectByName(name);
        if(selectType != null){
            throw new ProductTypeExistException("该商品类型已经存在");
        }

        // 如果不存在,准备添加
        // 前端页面只提供了类型名称,我们后端数据库中还需要状态
        // 因此,此处可以为状态设置一个默认值
        ProductType type = new ProductType();
        type.setName(name);
        type.setStatus(StatusConstant.PRODUCT_TYPE_STATUS_ENABLED);
        typeDao.insertType(type);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public List<ProductType> findAll() {
        List<ProductType> types = typeDao.selectAll();
        return types;
    }
}
